package logic

import (
	"context"
	"encoding/json"
	"time"
	"user_center/models/cache"
	"user_center/models/mysql"

	"user_center/userrpc/internal/svc"
	"user_center/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserListLogic {
	return &UserListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户信息列表展示
func (l *UserListLogic) UserList(in *userrpc.UserListRequest) (*userrpc.UserListResponse, error) {
	// todo: add your logic here and delete this line
	var users []mysql.User
	cacheData := cache.Rdb.Get(l.ctx, "userList").Val()
	if cacheData == "" {
		mysql.DB.Debug().Find(&users)
		jsonData, _ := json.Marshal(users)
		cache.Rdb.Set(l.ctx, "userList", jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &users)
	}

	var userList []*userrpc.UserList
	for _, user := range users {
		list := userrpc.UserList{
			Id:      int64(user.ID),
			Name:    user.Name,
			Sex:     user.Sex,
			Address: user.Address,
			Email:   user.Email,
		}
		userList = append(userList, &list)
	}
	return &userrpc.UserListResponse{
		List: userList,
	}, nil
}
